package com.example.compreshensiveshop.service.imp;

import com.example.compreshensiveshop.dao.CategoryDao;
import com.example.compreshensiveshop.dto.CategoryAddDTO;
import com.example.compreshensiveshop.dto.CategoryDeleteDTO;
import com.example.compreshensiveshop.dto.CategoryUpdateDTO;
import com.example.compreshensiveshop.po.CategoryPO;
import com.example.compreshensiveshop.service.CategoryService;
import com.example.compreshensiveshop.vo.CategoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Category Service Implementation
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    @Override
    public List<CategoryVO> getPublicCategory() {
    List<CategoryPO> categoryPOList = categoryDao.getPublicCategory();
    List<CategoryVO> categoryVOList = new ArrayList<>();
    for (CategoryPO categoryPO : categoryPOList){
        CategoryVO categoryVO = CategoryVO.builder()
                .categoryId(categoryPO.getId())
                .categoryName(categoryPO.getName())
                .sellerId(categoryPO.getSellerId())
                .build();
        categoryVOList.add(categoryVO);
    }
    return categoryVOList;
}

    @Override
    public List<CategoryVO> getSellerCategory(Long sellerId) {
        List<CategoryPO> categoryPOList = categoryDao.getSellerCategory(sellerId);
        List<CategoryVO> categoryVOList = new ArrayList<>();
        for (CategoryPO categoryPO : categoryPOList){
            CategoryVO categoryVO = CategoryVO.builder()
                    .categoryId(categoryPO.getId())
                    .categoryName(categoryPO.getName())
                    .sellerId(categoryPO.getSellerId())
                    .build();
            categoryVOList.add(categoryVO);
        }
        return categoryVOList;
    }
    @Override
    public void addCategory(CategoryAddDTO categoryAddDTO) {
        categoryDao.addCategory(categoryAddDTO.getCategoryName(), categoryAddDTO.getSellerId());
    }
    @Override
    public void updateCategory(CategoryUpdateDTO categoryUpdateDTO) {
        categoryDao.updateCategory(categoryUpdateDTO.getId(), categoryUpdateDTO.getCategoryName(), categoryUpdateDTO.getSellerId());
    }

    @Override
    public boolean deleteCategory(CategoryDeleteDTO categoryDeleteDTO) {
        // 检查分类下是否有商品
        int productCount = categoryDao.countProductsByCategory(categoryDeleteDTO.getId());

        if (productCount > 0) {
            // 分类下有商品，不允许删除
            return false;
        } else {
            // 分类下没有商品，允许逻辑删除
            categoryDao.logicalDeleteCategory(categoryDeleteDTO.getId());
            return true;
        }
    }

    @Override
    public String queryCategoryNameById(Long id) {
        return categoryDao.getCategoryByProductId(id);
    }



}